package com.NSoft.uuidgen;

import java.math.BigInteger;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

/**
 * The activator class controls the plug-in life cycle
 */
public class UUIDGenPlugin extends AbstractUIPlugin {

	// The plug-in ID
	public static final String PLUGIN_ID = "com.NSoft.uuidgen";

	// The shared instance
	private static UUIDGenPlugin plugin;
	
	/**
	 * The constructor
	 */
	public UUIDGenPlugin() {
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	/**
	 * Returns the shared instance
	 *
	 * @return the shared instance
	 */
	public static UUIDGenPlugin getDefault() {
		return plugin;
	}

	/**
	 * Returns an image descriptor for the image file at the given
	 * plug-in relative path
	 *
	 * @param path the path
	 * @return the image descriptor
	 */
	public static ImageDescriptor getImageDescriptor(String path) {
		return imageDescriptorFromPlugin(PLUGIN_ID, path);
	}
	
	public static String generateUUID()
	{
	    long millis = System.currentTimeMillis();
	    BigInteger millis_i = BigInteger.valueOf(millis);
	    BigInteger offset = new BigInteger("122192928000000000");
	    BigInteger multiplier = new BigInteger("10000");
	    BigInteger timestamp = millis_i.multiply(multiplier).add(offset);
	    
	    String timestamp_s = timestamp.toString(16);
	    
	    int clockID = (int)(Math.random() * Math.pow(2, 14));
	    String clockID_s = Integer.toHexString(clockID);
	    
	    // MAC address of unused Ethernet adapter
	    final String MAC_ADDRESS_ALWAYS_USE = "000C7631174F";
	    
	    StringBuilder uuid_builder = new StringBuilder();
	    uuid_builder.append(timestamp_s.substring(7));
	    uuid_builder.append("-");
	    uuid_builder.append(timestamp_s.substring(3, 7));
	    uuid_builder.append("-");
	    uuid_builder.append("1");
	    uuid_builder.append(timestamp_s.substring(0, 3));
	    uuid_builder.append("-");
	    uuid_builder.append("9");
	    uuid_builder.append(clockID_s.substring(1));
	    uuid_builder.append("-");
	    uuid_builder.append(MAC_ADDRESS_ALWAYS_USE);
	    return uuid_builder.toString();
	}
}
